<?php
	$db = NULL; $cur = isset($_GET["index"])?$_GET["index"]:"0"; $cometApi = NULL;
	
	function connect(){
		global $db;
		if ($db = new SQLiteDatabase('chat.db')) {
			$q = @$db->query('SELECT name,message FROM messages');
			if ($q === false)
				$db->queryExec('CREATE TABLE messages (name TEXT, message TEXT, unixtime INTEGER)');
		}
	}
	
	function write($data){
		global $cur,$cometApi;

		if(count($data)==0)
			print $cometApi->null;
		else
			foreach($data as $k=>$v){
				if(!$v["unixtime"])continue;
				print $cometApi->push("data.push({ name:'".$v["name"]."', message:'".$v["message"]."', unixtime:'".$v["unixtime"]."', time:".time().", cur:'".$cur."' });");
				$cur = $v["unixtime"];
			};
	}
	
	
	switch($_GET["task"]){
		case "read":
			
			require_once "pi_comet.php";
			$cometApi = new PIComet($_GET["PICometMethod"],$_GET["PICometName"]);
			header("Content-type: ".$cometApi->header);
		
			connect();

			for($i=0; $i<100; $i++){
				write($db->query("SELECT * FROM messages WHERE unixtime>$cur") );
				ob_flush();
				flush();
				usleep(100000);
			};
			
			break;
		case "add":
			flush();
			connect();
			$name = preg_replace("/[^\w\s\.\,\-\?\!]+/","_",$_POST["name"]);
			$message = preg_replace("/[^\w\s\.\,\-\?\!]+/","_",$_POST["message"]);
			$db->query("INSERT INTO messages (name,message,unixtime) VALUES ('$name','$message',".time().")");
			break;
		default:
			$fd = fopen ("../_html/form.html", "r");
			while (!feof ($fd)){
				print preg_replace('/src="/','src="../_html/',fgets($fd, 4096));
			};
			fclose ($fd);
			echo "
				<script type='text/javascript'>
					chat.env.url = { 'stream':'form.php?task=read', 'add':'form.php?task=add' };
				</script>
			";
	}

?>
